#! /usr/bin/env sh

# 文件类型预览函数
function category_pre()
{
    mime=$(file -bL --mime-type "$1")
    category=${mime%%/*}
    if [ -d "$1" ]; then
        exa -l --no-user --no-time --icons "$1" 2>/dev/null || ls --color=always "$1" 2>/dev/null || ls -G "$1"
    elif [ "$category" = text ]; then
        (bat -p --color=always "$1" || cat "$1") 2>/dev/null | head -1000
    elif [ "$category" = image ]; then
        # command -v ueberzug 2&>/dev/null && bash $HOME/.config/scripts/preview/img_preview.sh "$1"|| img2txt "$1"
        # command -v ueberzug 2&>/dev/null && bash $HOME/.config/scripts/preview/img_preview.sh "$1"|| timg "$1"
        command -v ueberzug 2&>/dev/null && bash $HOME/.config/scripts/preview/img_preview.sh "$1" || timg -E --frames=1 --loops=1 -g $(( $COLUMNS / 2 - 4 ))x$(( $FZF_PREVIEW_LINES * 2 )) "$1"
    else 
        echo $1 is a $category file
    fi
}

# Markdown文件预览
function markdown_pre(){
    # 如果系统有安装glow优先使用
    if [[ -x "$( which glow)" ]]; then
        # echo "[INFO] 有 glow"
        glow -s dark "$1" ;
    elif [[ -x "$( which bat)" ]]; then
        (bat -p --color=always "$1" || cat "$1") 2>/dev/null | head -1000
    else
        cat "$1";
    fi
}

# 文件预览
function file_pre(){
    case "$1" in
        *.pdf) pdftotext "$1" ;;
        # *.md) glow -s dark "$1" ;;
        *.md) markdown_pre  "$1";;
        *.zip) zipinfo "$1" ;;
        *.7z) 7z l "$1" ;;
        # *) bat --color=always --italic-text=always --style=numbers,changes,header --line-range :500 "$1" ;;
        *) category_pre  "$1";;
    esac
}

# 文件夹预览
function folder_pre() {
    exa -l --no-user --no-time --icons "$1" 2>/dev/null || ls --color=always "$1" 2>/dev/null || ls -G "$1"
}

#传入参数初步处理 防止传入的值不是文件路径 如 z.lua 传入的参数
if [[ -f "$1" ]]; then
    file_pre "$1";
elif [[ -d "$1" ]]; then
    # echo "$1";
    folder_pre "$1";
else
    # echo "$1";
    # 如 z.lua 的参数预处理,截取文件夹路径
    path="$(echo $1 |  awk ' / / {print $2}')"

    # echo "$path";
    if [[ -f "$path" ]]; then
        file_pre "$path";
    elif [[ -d "$path" ]]; then
        folder_pre "$path";
    else
        echo "$1";
    fi
fi


